﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RN.ERP.Web.PersonService;
using Newtonsoft.Json;
using RN.ERP.Web.ModelService;
using Telerik.Web.UI;
using Fly.Common.Linq;
using System.Web.UI.HtmlControls;

namespace RN.ERP.Web.Exam
{
    public partial class SelectEmps : BasePage
    {
        PersonServiceClient client = new PersonServiceClient();
        public string AppID
        {
            get
            {
                return HttpContext.Current.Application[ApplicationConstant.APPLICATION_ID].ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                hidType.Value = Request.QueryString["type"];//类型：0添加，1查看，2修改，3更换人员
                hidId.Value = Request.QueryString["id"];//主表id
                if (hidType.Value == "3")//更换人员
                {
                    tbBm.Visible = false;
                    tbChange.Visible = true;
                }
                else
                {
                    if (hidType.Value == "1")//查看
                    {
                        lbBM.Enabled = false;
                    }
                    BindData();//绑定已有数据
                }
                BindQCDDL();
            }
        }

        protected void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            BindEmp();//绑定人员列表
        }

        /// <summary>
        /// 获取当前登录专家信息
        /// </summary>
        /// <param name="empGuid">专家Guid</param>
        private tb_Emp_Manager GetEmpManager(string empGuid)
        {
            Guid empGuid1 = Guid.Empty;
            Guid.TryParse(empGuid, out empGuid1);
            tb_Emp_Manager emp = new tb_Emp_Manager();

            using (PersonService.PersonServiceClient client = new PersonService.PersonServiceClient())
            {
                QueryPersonInfoCondition queryCondition = new QueryPersonInfoCondition()
                {
                    EmpGuid = new ParameterValue<Guid> { V = empGuid1, O = OptEnum.Equal }
                };
                List<QueryPersonInfoCondition> query = new List<QueryPersonInfoCondition>() { queryCondition };
                string queryStr = JsonConvert.SerializeObject(query);
                var manages = client.GetEmpManagersAllList(1, 0, queryStr, UserInfo.CurrentArea);
                emp = JsonConvert.DeserializeObject<List<tb_Emp_Manager>>(manages).FirstOrDefault();
            }
            return emp;
        }

        protected void lbSearch_Click(object sender, EventArgs e)
        {
            RadGrid1.CurrentPageIndex = 0;
            BindEmp();
            RadGrid1.DataBind();
        }

        protected void lbBM_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(ddlQC.SelectedValue))
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('请选择期次！');", true);
            }
            else
            {
                if (!string.IsNullOrEmpty(hidEmps.Value))
                {
                    OperationResult result = new OperationResult();
                    result.Result = false;
                    result.Message = "操作失败";
                    
                    Exam_QC examqc = JsonConvert.DeserializeObject<Exam_QC>(client.GetExamQC(int.Parse(ddlQC.SelectedValue)));
                    ExamBM bmInfo = new ExamBM();
                    tb_Emp_Manager empManager = GetEmpManager(UserInfo.CorpUserGuid);

                    if (!string.IsNullOrEmpty(hidId.Value))
                    {
                        bmInfo.ID = int.Parse(hidId.Value);
                    }
                    bmInfo.QCId = int.Parse(ddlQC.SelectedValue);
                    bmInfo.QCTitle = ddlQC.SelectedItem.Text;
                    bmInfo.AreaCode = empManager.DBType;
                    bmInfo.CorpName = UserInfo.Name;
                    bmInfo.CorpUserGuid = Guid.Parse(UserInfo.CorpUserGuid);
                    bmInfo.BMDate = DateTime.Now;
                    bmInfo.StartDate = examqc.StartDate;
                    bmInfo.EndDate = examqc.EndDate;
                    bmInfo.IsDel = false;
                    bmInfo.IsrtDate = DateTime.Now;
                    List<ExamBMSub> bmsub = new List<ExamBMSub>();
                    string[] strs = hidNote.Value.Split('@');
                    for (int i = 0; i < strs.Length; i++)
                    {
                        ExamBMSub sub = new ExamBMSub();
                        EmpInfo emp = JsonConvert.DeserializeObject<EmpInfo>(strs[i]);
                        if (!string.IsNullOrEmpty(hidId.Value))
                        {
                            sub.TreeId = int.Parse(hidId.Value);
                        }
                        sub.EmpGuid = emp.EmpGuid;
                        sub.EmpName = emp.Name;
                        sub.IDCard = emp.IDCard;
                        sub.IsDel = false;
                        sub.IsrtDate = DateTime.Now;
                        bmsub.Add(sub);
                    }
                    bmInfo.ExamBMSub = bmsub.ToArray();
                    if (hidType.Value == "0")
                    {
                        result = JsonConvert.DeserializeObject<ModelService.OperationResult>(client.AddBMInfo(JsonConvert.SerializeObject(bmInfo)));
                    }
                    else if (hidType.Value == "2")
                    {
                        result = JsonConvert.DeserializeObject<ModelService.OperationResult>(client.EditBMInfo(JsonConvert.SerializeObject(bmInfo)));
                    }
                    if (result.Result)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('" + result.Message + "','',CloseWin);", true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('" + result.Message + "');", true);
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('请选择人员！');", true);
                }
            }
        }

        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (!string.IsNullOrEmpty(hidEmps.Value))
            {
                string[] strs = hidEmps.Value.Split(',');
                for (int i = 0; i < RadGrid1.Items.Count; i++)
                {
                    HtmlInputCheckBox cbox = (HtmlInputCheckBox)RadGrid1.Items[i].Cells[0].FindControl("ckbChoose");
                    string empguid = cbox.Value;
                    if (strs.Contains(empguid))
                    {
                        cbox.Checked = true;
                    }
                }
            }
        }

        protected void lbChange_Click(object sender, EventArgs e)
        {
            Guid afterGuid = Guid.Empty;
            string afterName = string.Empty;
            for (int i = 0; i < RadGrid1.Items.Count; i++)
            {
                HtmlInputCheckBox cbox = (HtmlInputCheckBox)RadGrid1.Items[i].Cells[0].FindControl("ckbChoose");
                if (cbox.Checked)
                {
                    afterGuid = Guid.Parse(cbox.Value);
                    afterName = cbox.Attributes["empname"].ToString();
                    break;
                }
            }
            if (afterGuid != Guid.Empty)
            {
                Exam_ChangeEmp change = new Exam_ChangeEmp();
                change.ExamSubId = int.Parse(Request.QueryString["subid"]);
                change.CorpUserGuid = Guid.Parse(UserInfo.CorpUserGuid);
                change.CorpName = UserInfo.Name;
                change.BeforeGuid = Guid.Parse(Request.QueryString["guid"]);
                change.BeforeName = Request.QueryString["name"];
                change.AfterGuid = afterGuid;
                change.AfterName = afterName;
                change.Reason = txtReason.Text;
                change.IsrtDate = DateTime.Now;
                change.IsDel = false;
                OperationResult result = JsonConvert.DeserializeObject<OperationResult>(client.BMChangeEmp(JsonConvert.SerializeObject(change)));
                if (result.Result)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('" + result.Message + "','',CloseWin1);", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('" + result.Message + "');", true);
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "$.ligerDialog.warn('请选择更换人员！');", true);
            }
        }

        private void BindEmp()
        {
            if (hidType.Value == "1")//查看，只显示报名人员列表
            {
                ExamBM exam = JsonConvert.DeserializeObject<ExamBM>(client.GetBMEmpList(int.Parse(hidId.Value)));
                ExamBMSub[] list = exam.ExamBMSub;
                List<EmpInfo> emplist = new List<EmpInfo>();
                foreach (var item in list)
                {
                    EmpInfo info = new EmpInfo();
                    info.EmpGuid = item.EmpGuid;
                    info.Name = item.EmpName;
                    info.IDCard = item.IDCard;
                    emplist.Add(info);
                }
                if (!string.IsNullOrEmpty(txtName.Text.Trim()))
                {
                    emplist = emplist.Where(m => m.Name.Contains(txtName.Text.Trim())).ToList();
                }
                if (!string.IsNullOrEmpty(txtIDCard.Text.Trim()))
                {
                    emplist = emplist.Where(m => m.IDCard.Contains(txtIDCard.Text.Trim())).ToList();
                }
                RadGrid1.AllowCustomPaging = true;
                RadGrid1.VirtualItemCount = emplist.Count();
                RadGrid1.DataSource = emplist;
            }
            else
            {
                ModelService.QueryPersonInfoCondition queryCondition = new ModelService.QueryPersonInfoCondition();
                queryCondition.CorpGuid = new ParameterValue<Guid> { V = Guid.Parse(UserInfo.CorpUserGuid), O = OptEnum.Equal };
                if (!string.IsNullOrEmpty(txtName.Text.Trim()))
                {
                    queryCondition.Name = new ParameterValue<string> { V = txtName.Text.Trim(), O = OptEnum.Like };
                }
                if (!string.IsNullOrEmpty(txtIDCard.Text.Trim()))
                {
                    queryCondition.IDCard = new ParameterValue<string> { V = txtIDCard.Text.Trim(), O = OptEnum.Like };
                }
                List<ModelService.QueryPersonInfoCondition> query = new List<ModelService.QueryPersonInfoCondition>() { queryCondition };
                string queryStr = JsonConvert.SerializeObject(query);
                int pageCount = RadGrid1.CurrentPageIndex + 1;
                int pageSize = RadGrid1.PageSize;
                RadGrid1.AllowCustomPaging = true;
                if (hidType.Value == "3")//更换人员，显示未报名人员
                {
                    ExamBM exam = JsonConvert.DeserializeObject<ExamBM>(client.GetBMEmpList(int.Parse(hidId.Value)));
                    ExamBMSub[] list = exam.ExamBMSub;
                    ddlQC.SelectedValue = exam.QCId.ToString();
                    var arr = list.Select(m => m.EmpGuid).ToArray();//已报名人员guid集合
                    var emplist = JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(client.GetEmpManagersAllList(0, 0, queryStr, UserInfo.CurrentArea));//所有人员集合
                    var emps = emplist.Where(m => !arr.Contains(m.EmpGuid)).ToList();//排除已报名人员
                    RadGrid1.VirtualItemCount = emps.Count();
                    RadGrid1.DataSource = emps;
                }
                else
                {
                    RadGrid1.VirtualItemCount = client.GetEmpManagersAllCount(queryStr, UserInfo.CurrentArea);
                    RadGrid1.DataSource = JsonConvert.DeserializeObject<List<ModelService.tb_Emp_Manager>>(client.GetEmpManagersAllList(pageCount, pageSize, queryStr, UserInfo.CurrentArea));
                }
            }
        }

        private void BindData()
        {
            if (!string.IsNullOrEmpty(hidId.Value))
            {
                ExamBM exam = JsonConvert.DeserializeObject<ExamBM>(client.GetBMEmpList(int.Parse(hidId.Value)));
                ExamBMSub[] list = exam.ExamBMSub;
                ddlQC.SelectedValue = exam.QCId.ToString();
                ddlQC.Enabled = false;
                ////获取人员guid集合
                var arr = list.Select(m => m.EmpGuid).ToArray();
                hidEmps.Value = string.Join(",", arr);
                ////获取人员name集合
                var names = list.Select(m => m.EmpName).ToArray();
                hidNames.Value = string.Join(",", names);
                foreach (var item in list)
                {
                    EmpInfo info = new EmpInfo();
                    info.EmpGuid = item.EmpGuid;
                    info.Name = item.EmpName;
                    info.IDCard = item.IDCard;
                    hidNote.Value = hidNote.Value + JsonConvert.SerializeObject(info) + "@";
                }
                hidNote.Value = hidNote.Value.TrimEnd('@');
            }
            else if (!string.IsNullOrEmpty(Request.QueryString["qcid"]))
            {
                ddlQC.SelectedValue = Request.QueryString["qcid"];
            }
        }

        private void BindQCDDL()
        {
            int count = 0;
            var qc = JsonConvert.DeserializeObject<List<ModelService.Exam_QC>>(client.GetExamQCList
                          ("QC", UserInfo.RoleId, "BmQCList.aspx", AppID, 0, 0, out count));
            ddlQC.DataSource = qc;
            ddlQC.DataValueField = "ID";
            ddlQC.DataTextField = "Title";
            ddlQC.DataBind();
            ddlQC.Items.Insert(0, new ListItem("--请选择--", ""));
        }

        public class EmpInfo
        {
            public Guid? EmpGuid { get; set; }
            public String Name { get; set; }
            public String IDCard { get; set; }
        }

    }
}